<template>
  <el-dialog
    v-model="dialogVisible"
    title="合同信息"
    width="50%"
    :before-close="handleClose"
  >
    <div class="tab4-dialog-hetong">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="110px"
        inline
      >
        <el-form-item prop="customer_name" label="客户名称">
          <el-input
            disabled
            readonly
            placeholder="客户名称"
            v-model="dataInfo.customer_name"
          />
        </el-form-item>
        <el-form-item prop="order_name" label="合同名称">
          <el-input placeholder="合同名称" v-model="ruleForm.order_name" />
        </el-form-item>
        <el-form-item prop="order_no" label="合同编号">
          <el-input
            placeholder="合同编号"
            disabled
            v-model="ruleForm.order_no"
          />
        </el-form-item>
        <el-form-item prop="order_uid" label="签署人">
          <el-tree-select
            default-expand-all
            node-key="id"
            filterable
            v-model="ruleForm.order_uid"
            :data="userOptions"
            check-strictly
            :render-after-expand="false"
            :props="{
              label: 'name',
            }"
            style="width: 100%"
            placeholder="签署人"
            clearable
          >
          </el-tree-select>
        </el-form-item>

        <el-form-item label="签署日期" prop="order_date">
          <el-date-picker
            style="width: 100%"
            v-model="ruleForm.order_date"
            type="date"
            placeholder="签署日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item prop="is_virtual" label="虚拟合同">
          <el-radio-group v-model="ruleForm.is_virtual">
            <el-radio :label="0" size="large">否</el-radio>
            <el-radio :label="1" size="large">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="contact_id" label="客户签署人">
          <el-select
            style="width: 100%"
            v-model="ruleForm.contact_id"
            placeholder="客户签署人"
            filterable
            clearable
          >
            <el-option
              v-for="item in userData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="开始/结束日期">
          <el-date-picker
            v-model="ruleForm.datetimerange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item prop="amount_real" label="合同金额（元）">
          <el-input
            placeholder="合同金额（元）"
            v-model="ruleForm.amount_real"
          />
        </el-form-item>
        <el-form-item prop="owner_by" label="销售">
          <el-tree-select
            default-expand-all
            node-key="id"
            filterable
            v-model="ruleForm.owner_by"
            :data="userOptions"
            check-strictly
            :render-after-expand="false"
            :props="{
              label: 'name',
            }"
            style="width: 100%"
            placeholder="选择销售"
            clearable
          >
          </el-tree-select>
        </el-form-item>
        <el-form-item prop="has_fax" label="是否含税">
          <el-radio-group v-model="ruleForm.has_fax">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="is_invoice" label="是否开具发票">
          <el-radio-group v-model="ruleForm.is_invoice">
            <el-radio :label="0">不开票</el-radio>
            <el-radio :label="1">开票</el-radio>
            <el-radio :label="2">开收据</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="truck_price" label="运费(元)">
          <div style="white-space: nowrap">
            <el-input
              :disabled="inputType"
              placeholder="运费"
              v-model="ruleForm.truck_price"
            />
            <span style="color: #8c8d8f; font-size: 12px">
              *运费包含在合同金额里
            </span>
          </div>
        </el-form-item>
        <el-form-item prop="" label="合同附件" style="width: 100%">
          <el-upload
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :on-change="fileOnChange"
            :show-file-list="false"
          >
            <div class="file-btn">
              <el-button type="primary" size="small"> 文件上传 </el-button>
            </div>
          </el-upload>
          <div class="file-list" v-if="fileList.length > 0" style="width: 100%">
            <div class="file-list-item" v-for="(item, i) in fileList">
              <span> {{ item.file_name || item.name }}</span>
              <el-icon class="close" @click="fileRemove(i)">
                <IEpClose />
              </el-icon>
            </div>
          </div>
        </el-form-item>
        <el-form-item prop="contract" label="相关合同">
          <el-select
            v-model="ruleForm.contract"
            placeholder="相关合同"
            style="width: 100%"
            multiple
          >
            <el-option
              v-for="item in contractOptions"
              :key="item.id"
              :label="item.order_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="remark" label="备注" style="width: 100%">
          <el-input
            placeholder="备注"
            type="textarea"
            :rows="2"
            v-model="ruleForm.remark"
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="submit"> 提交 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { fileApi } from "@/plugins/api/upload";
import { baseApi } from "@/plugins/api/customer/manage/tab4.js";
const props = defineProps({
  dataInfo: {
    type: Object,
    default: {},
  },
  // 合同
  contractOptions: {
    type: Array,
    default: [],
  },
  // 公司签署人
  userOptions: {
    type: Array,
    default: [],
  },
  // 客户签署人
  userData: {
    type: Array,
    default: [],
  },
});
let ruleForm = ref({});
let rules = {
  customer_name: [
    {
      required: true,
      message: "客户名称",
      trigger: "blur",
    },
  ],
  own_type: [
    {
      required: true,
      message: "客户类型",
      trigger: "change",
    },
  ],
};
let dialogVisible = ref(false);
function handleClose(done) {
  ElMessageBox.confirm("是否确定关闭此对话框?")
    .then(() => {
      done();
    })
    .catch(() => {});
}
let title = ref("");
let submitType = ref("");
let ruleFormRef = ref(null);
function initFun(row) {
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields();
  }
  ruleForm.value = { ...row };
  ruleForm.value.is_virtual = row.is_virtual; //是否是虚拟合同
  ruleForm.value.has_fax = row.has_fax; //是否含税
  ruleForm.value.is_invoice = row.is_invoice; //是否开具发票
  fileList.value = []; //清空文件列表
  if (row.files_arr) {
    fileList.value = row.files_arr.map((item) => {
      return item;
    });
  }
  if (row.contracts) {
    ruleForm.value.contract = row.contracts.split(",").map((item) => {
      return parseInt(item);
    });
  }
  if (row.start_date && row.end_date) {
    ruleForm.value.datetimerange = [];
    ruleForm.value.datetimerange.push(row.start_date);
    ruleForm.value.datetimerange.push(row.end_date);
  }

  dialogVisible.value = true;
}
const emit = defineEmits(["refreshList"]);
function submit() {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      if (
        ruleForm.value.datetimerange &&
        ruleForm.value.datetimerange.length == 2
      ) {
        ruleForm.value.start_date = ruleForm.value.datetimerange[0];
        ruleForm.value.end_date = ruleForm.value.datetimerange[1];
      }
      if (fileList.value.length > 0) {
        ruleForm.value.files = [...fileList.value];
      }
      if (ruleForm.value.contract) {
        ruleForm.value.contracts = ruleForm.value.contract.join(",");
      }
      baseApi(ruleForm.value).then(() => {
        ElMessage.success("编辑成功！");
        dialogVisible.value = false;
        emit("refreshFun");
      });
    }
  });
}

// 文件上传
let fileList = ref([]);
function fileOnChange(file) {
  let formData = new FormData();
  formData.append("file", file.raw);
  fileApi(formData).then((resp) => {
    if (resp) {
      fileList.value.push({
        name: resp.file_name,
        url: resp.file_url,
      });
    } else {
      ElMessage.danger("上传失败！请重新上传！");
    }
  });
}
function fileRemove(i) {
  fileList.value.splice(i, 1);
}

onMounted(() => {});
defineExpose({
  initFun,
});
</script>
<style scoped lang="scss">
.tab4-dialog-hetong {
  h4 {
    margin: 0;
    margin-bottom: 20px;
  }

  :deep(.el-form-item) {
    width: 50%;
    margin-right: 0;
  }

  .goods-head {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;

    span {
      margin-right: 20px;
    }
  }

  .file-list {
    .file-list-item {
      display: flex;

      span,
      .close {
        align-self: center;
      }

      .close {
        margin-left: 20px;

        &:hover {
          cursor: pointer;
          color: rgb(26, 145, 236);
        }
      }
    }
  }
}
</style>
